articles

Home / DeveloperSection / Articles / ASP.NET MVC5 Razor With jQuery

ASP.NET MVC5 Razor With jQuery

Anupam Mishra6724 11-Mar-2016
Introduction:

 

In this article I will take a simplest way to create a simple MVC 5 application for beginners. If you are a beginner and want to be find how to create modal, controller and their views with extra plugins such as jQuery. If you are not comfortable with jQuery so, don’t worry you have skip those topic and concentrate with rest one.

In this article, I have explain about how to create a modal, how to create a controller & How to bind their views with its data modal. I have also using a jQuery for extra enhancements.  

Background: 

MVC is a Framework which is use for building a web application with the facilitate of MVC Design. It’s 100% extensible.

Here are three patterns for implemented and design for MVC Application. 

Model:  The Model pattern will handled the logic of the application data. A model is easy to get both controller and view. Pass the data from controller to view by the Model.

   View: The view pattern exhibit the user interface of an application. This interface shaped with the Model data.

  Controller: The controllers will interaction with the user request. Controller watch out the whole execution of request. It’s got the request from the web server and checks the data necessities. 

  Model:

 I have using a code first approach for creating a model. Here, I have created an Employee model. For creating an employee model. Follow the following steps:

 1.      Right click on Model Folder

2.      Choose “Add” navigation

3.      Choose “Class” and Select

4.      Renaming the class file name “Employee”

5.      Then paste the below code 

 

   

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
namespace Demo.Models
{
    publicclassEmployee
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        publicint EmpID { get; set; }
        [Required]
        [Display(Name="Full Name")]
        publicstring FullName { get; set; }
        [Required]
        [Display(Name="Email-id")]
        [DataType(DataType.EmailAddress)]
        publicstring Email { get; set; }
        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters  long.", MinimumLengt h = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        publicstring Password { get; set; }
        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        publicstring ConfirmPassword { get; set; }
        [Display(Name="Date-Of-Birth")]
        publicDateTime DoB { get; set; }
        [Display(Name="Address")]
        publicstring Address { get; set; }
        [Display(Name="City")]
        publicstring Town { get; set; }
        [Display(Name="Country")]
        publicstring County { get; set; }
        [Display(Name="IsActive")]
        publicbool IsActive { get; set; }
}
    publicclassEmployeeDBContext : DbContext
    {
        publicDbSet<Employee> Employees { get; set; }
    }
}

 

Controller:     
 Here, I have created an EmployeeController. For creating an EmployeController.
Follow the following steps:


1.      Right click on Controller Folder

2.      Choose “Add” navigation

3.      Choose “Controller” and Select

4.      Renaming the Controller file name “EmployeeController”

5.      In Scaffolding Option choose template “MVC controller with read/write actions and views,using    Entity Framework”

6.      Select Model class “Employee(****.Models)”

7.      Choose Data Context class :”EmployeeDBContext(****.Models)”

8.      View is by default Razor and other one remaining same.

9.      Click add button

***** representing your namespace


Views:

It will created a folder with the same name as controller name  in Views section and it will also create 5 views namely Index, Create, Edit, Delete, Details automatically. Such as look like this:

ASP.NET MVC5 Razor With jQuery

 Index Page:

 Here, it is a simple index page that are display records and attached with other views of loaded functionality for curd operation.

@model IEnumerable<Demo.Models.Employee>
 
@{
    ViewBag.Title = "Index";
}
 
<h2>Index</h2>
 
<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model=> model.FullName)
        </th>
        <th>
            @Html.DisplayNameFor(model=> model.Email)
        </th>
         <th>
            @Html.DisplayNameFor(model=> model.DoB)
        </th>
        <th>
            @Html.DisplayNameFor(model=> model.Address)
        </th>
        <th>
            @Html.DisplayNameFor(model=> model.Town)
        </th>
        <th>
            @Html.DisplayNameFor(model=> model.County)
        </th>
        <th>
            @Html.DisplayNameFor(model=> model.IsActive)
        </th>
        <th></th>
    </tr>
 
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem=> item.FullName)
        </td>
        <td>
            @Html.DisplayFor(modelItem=> item.Email)
        </td>
       <td>
            @Html.DisplayFor(modelItem=> item.DoB)
        </td>
        <td>
            @Html.DisplayFor(modelItem=> item.Address)
        </td>
        <td>
            @Html.DisplayFor(modelItem=> item.Town)
        </td>
        <td>
            @Html.DisplayFor(modelItem=> item.County)
        </td>
        <td>
            @Html.DisplayFor(modelItem=> item.IsActive)
        </td>
        <td>
            @Html.ActionLink("Edit","Edit", new { id=item.EmpID }) |
            @Html.ActionLink("Details", "Details", new { id=item.EmpID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.EmpID })
        </td>
    </tr>
}
 
</table>
 

 

Output:


ASP.NET MVC5 Razor With jQuery

Search:

The search functionality for searching employee with name and its other related


areas.


Now, I applied some jQuery code for better look & feel and using html for data will


be inside a table. Here, the code of searching and some basic filtering in action


result Index of EmployeeController. Code is as follows:

publicActionResult Index(string searchString,string currentFilter,string sortOrder)
        {
            ViewBag.CurrentSort = sortOrder;
            ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
            ViewBag.DateSortParm =sortOrder == "Date" ? "date_desc" : "Date";
            ViewBag.CurrentFilter= searchString;
            var emp = from s in db.Employees
                           select s;
            if (!String.IsNullOrEmpty(searchString))
            {
                emp = emp.Where(s=> s.FullName.ToUpper() .Contains(searchString.ToUpper())
                   || s.Email.ToUpper().Contains(searchString.ToUpper()) ||s.Address.ToUpper().Contains(searchString.ToUpper()) ||s.County.ToUpper().Contains(searchString.ToUpper()));
            }
            switch (sortOrder)
            {
                case"name_desc":
                    emp = emp.OrderByDescending(s => s.FullName);
                    break;
                 case"date_desc":
                    emp = emp.OrderByDescending(s => s.DoB);
                    break;
                default//Name ascending
                    emp = emp.OrderBy(s => s.EmpID);
                    break;
            }
              return View(emp.ToList());
        }

 

Index.cshtml
@model IEnumerable<Demo.Models.Employee>
 
@{
    ViewBag.Title = "Employee Home";
}
<scriptsrc="~/Scripts/jquery-1.8.2.min.js"></script>
<linkhref="~/Content/Site.css"rel="stylesheet"/>
<scriptsrc="~/Scripts/jquery-ui-1.8.24.js"></script>
<h2>Home</h2>
 
<p>
    <scriptsrc="~/Scripts/modernizr-2.6.2.js"></script>
    @using (Html.BeginForm("Create", "Employee"))
    {
   
        <inputtype="submit"value="Create New Employee"style="padding: 5px5px5px5px"/>
        
    }
</p>
 @using (Html.BeginForm("Index", "Employee", FormMethod.Get))
{
    <p>
       Search: @Html.TextBox("SearchString", ViewBag.CurrentFilter asstring
        <inputtype="submit"value="Search"/>
    </p>
}
 
<tableid="emp">
    <tr>
        <th>
            @Html.ActionLink("Full Name", "Index", new { sortOrder = ViewBag.NameSortParm })
        </th>
        <th>
            @Html.DisplayNameFor(model=> model.Email))
        </th>
        <th>
            @Html.ActionLink("D-O-B","Index", new { sortOrder = ViewBag.DateSortParm })
        </th>
        <th>
            @Html.DisplayNameFor(model=> model.Address)
        </th>
        <th>
            @Html.DisplayNameFor(model=> model.Town)
        </th>
        <th>
            @Html.DisplayNameFor(model=> model.County)
        </th>
        <th>
            @Html.DisplayNameFor(model=> model.IsActive)
        </th>
        <th>Actions
        </th>
 
    </tr>
 
    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem=> item.FullName)
            </td>
            <td>
                @Html.DisplayFor(modelItem=> item.Email)
            </td>
            <td>
                @Html.DisplayFor(modelItem=> item.DoB)
            </td>
            <td>
                @Html.DisplayFor(modelItem=> item.Address)
            </td>
            <td>
                @Html.DisplayFor(modelItem=> item.Town)
            </td>
            <td>
                @Html.DisplayFor(modelItem=> item.County)
            </td>
            <td>
                @Html.DisplayFor(modelItem=> item.IsActive)
            </td>
            <td>
            @Html.ActionLink("Edit","Edit", new { id = item.EmpID }) |
            @Html.ActionLink("Details", "Details", new { id = item.EmpID }) |
            @Html.ActionLink("Delete", "Delete", new { id = item.EmpID })
            </td>
        </tr>
     
    }
 
</table>
  @Url.Action("Index", new { sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter });
<style>
    table #emp {
        width:initial;
        background-color:#f1f1c1;
        position:absolute;
    }
 
        table #emptr:nth-child(even) {
            background-color:#ccc;
        }
 
        table #emptr:nth-child(odd) {
            background-color: #fff;
        }
 
        table #empth {
            color:black;
            background-color:yellow;
        }
 
    table, th, td {
        border:2pxsolidblack;
    }
 
    table, th, td {
        border:1pxsolidblack;
        border-collapse: collapse;
    }
 
    table, th, td {
        border:1pxsolidblack;
        border-collapse: collapse;
    }
 
    th, td {
        padding: 5px;
    }
 
   </style> 

 

 Output:
ASP.NET MVC5 Razor With jQuery
After searching operation, output is as follow:
ASP.NET MVC5 Razor With jQuery
References:

·                Working with Model

·         Working with Controller

·         https://jquery.com/

·         http://www.asp.net/mvc/mvc5


Leave Comment

Comments

Liked By